<template>
  <div class="banner-page">
    <div class="add-button">
      <el-button type="success" round size="mini" @click="handleAdd">新增+</el-button>
    </div>
    <!-- 轮播图管理 -->
    <el-table
      :data="bannerList"
      border
      style="width: 100%"
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column align="center" label="图片" width="220" height="60">
        <template slot-scope="scope">
          <img :src="scope.row.carousel" :alt="scope.row.carousel" style="width: 100%; height: 100%">
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否现在启用" width="250">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.is_use"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="启用"
            inactive-text="不启用"
            @change="changeSwitch(scope.row._id, scope.row.is_use)"
          /></template>
      </el-table-column>
      <el-table-column align="center" label="更新日期">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          {{ scope.row.date }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            round
            @click="handleEdit(scope.row._id, scope.row.is_use)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            round
            @click="handleDelete(scope.row._id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增轮播图弹窗 -->
    <el-dialog title="新增轮播图" :visible.sync="dialogTableVisible" :before-close="beforeClose">
      <!-- 图片上传 -->
      <div class="upload-box">
        <el-upload
          ref="upload"
          class="upload-demo"
          action="action"
          :auto-upload="false"
          :http-request="handleUpload"
          :before-upload="beforeUpload"
          :on-change="handleChange"
          :limit="1"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </div>
      <!-- 启用状态 -->
      <div class="state-box">
        <span>是否现在启用：</span>
        <el-select v-model="is_use" size="mini" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left">{{ item.label }}</span>
          </el-option>
        </el-select>
      </div>
      <!-- 取消or确定 -->
      <div class="msg-btn">
        <el-button type="primary" round @click="cancale">取消</el-button>
        <el-button type="success" round @click="confirm">提交</el-button>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        background
        :current-page.sync="Pagination.pageNumber"
        :page-size="Pagination.pageSize"
        layout="total, prev, pager, next"
        :total="Pagination.total"
      />
    </div>
  </div>
</template>

<script>
import { getBannerList, addBanner, editBanner, deleteBanner, isUseBanner } from '@/api/banner'
export default {
  data() {
    return {
      bannerList: [],
      Pagination: {
        pageNumber: 0,
        pageSize: 10,
        total: 0
      },
      dialogTableVisible: false,
      formData: null,
      is_use: false,
      isAdd: false,
      isHaveData: false,
      ID: null,
      options: [
        {
          label: '启用',
          value: true
        },
        {
          label: '不启用',
          value: false
        }
      ]
    }
  },
  created() {
    this.getbanner(this.Pagination)
  },
  methods: {
    // 获取轮播图列表
    async getbanner(Pagination) {
      try {
        const res = await getBannerList(Pagination)
        this.bannerList = res.data
        this.Pagination = res.pagination
      } catch (err) {
        console.log(err)
      }
    },
    // 上传文件之前的钩子函数
    beforeUpload(file) {
      const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (type !== 'jpg' && type !== 'png' && type !== 'jpeg') {
        this.$message.error('只能上传jpg/png/jpeg文件')
        this.isHaveData = false
        return false
      }
      if (file.size > 500 * 1024) {
        this.$message.error('文件大小不能超过500kb')
        this.isHaveData = false
        return false
      }
      const formData = new FormData()
      formData.append('files', file)
      formData.append('is_use', this.is_use)
      this.formData = formData
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file) {
      if (file.size) {
        this.isHaveData = true
      } else {
        this.isHaveData = false
      }
    },
    // 新增事件
    handleAdd() {
      this.dialogTableVisible = true
      this.isAdd = true
      this.isHaveData = false
    },
    // 编辑事件
    handleEdit(id, is_use) {
      this.dialogTableVisible = true
      this.isAdd = false
      this.ID = id
      this.is_use = is_use
      this.isHaveData = false
    },
    // 新增/编辑轮播图
    async handleUpload() {
      if (this.isAdd === true) {
        try {
          const formdata = this.formData
          await addBanner(formdata)
          this.$message.success('上传成功')
          this.dialogTableVisible = false
          this.isHaveData = false
          this.$refs.upload.clearFiles()
          // 重新拉取数据
          this.getbanner(this.Pagination)
        } catch (err) {
          this.$message.error('上传失败')
        }
      } else {
        try {
          const formData = this.formData
          const res = await editBanner(this.ID, formData)
          console.log(res)
          this.$message.success('编辑成功')
          this.dialogTableVisible = false
          this.isHaveData = false
          this.$refs.upload.clearFiles()
          // 重新拉取数据
          this.getbanner(this.Pagination)
        } catch (err) {
          this.$message.error('编辑失败')
        }
      }
    },
    // 关闭弹窗之前的钩子函数
    cancale() {
      this.formData = null
      this.$refs.upload.clearFiles()
      this.dialogTableVisible = false
      this.is_use = false
      this.isHaveData = false
    },
    // 手动上传文件
    confirm() {
      if (this.isHaveData === false) {
        this.$message.error('请选择上传文件')
        return false
      }
      this.$refs.upload.submit()
    },
    // 删除轮播图
    handleDelete(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteBanner(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getbanner(this.Pagination)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 切换启用状态
    async changeSwitch(id, value) {
      const is_use = value
      try {
        await isUseBanner({
          id,
          is_use
        })
        this.$message.success('切换成功')
        // 重新拉取数据
        this.getbanner(this.Pagination)
      } catch (err) {
        console.log(err)
        this.$message.error('切换失败')
      }
    },
    // 关闭弹窗之前的钩子函数
    beforeClose() {
      this.formData = null
      this.$refs.upload.clearFiles()
      this.dialogTableVisible = false
      this.is_use = false
      this.isHaveData = false
    }
  }
}
</script>

<style lang="scss" scoped>
.banner-page {
  margin: 0 20px;
}
.add-button, .msg-btn {
  display: flex;
  padding: 20px 0;
  justify-content: flex-end;
}

.state-box {
  padding: 20px 0;
}
.upload-box {
  width: 250px;
}
.block {
  margin-top: 20px;
  text-align: center;
}
</style>
